import * as fs from 'fs';
import ApiDecorator from '../decorator/apiDecorator';
import DtoDecorator from '../decorator/dtoDecorator';

export default class SwaggerUtil {

    public json: any = {
        swagger: "2.0",
        info: {
            "description": "# swagger-bootstrap-ui-demo RESTful APIs",
            "version": "1.0",
            "title": "swagger-bootstrap-ui-demo RESTful APIs",
            "termsOfService": "http://www.xx.com/",
            "contact": {
                "name": "xx@qq.com"
            }
        },
        host: "127.0.0.1:7001",
        basePath: "/api",
        tags: [],
        paths: {},
        securityDefinitions: {},
        definitions: {}
    }


    /**创建swagger */
    public genSwaggerDocs() {
        this.genTags();
        this.genApis();
        fs.writeFileSync("app/public/static/api-doc.json", JSON.stringify(this.json));
    }

    /**生成Api */
    public genApis() {
        ApiDecorator.routes.forEach(p => {
            const element = ApiDecorator.prefix[p.constructor.name];
            let path = element.prefix + p.path;
            this.json.paths[path] = this.json.paths[path] ?? {};
            let parameters: any[] = [];
            if (p.in) {
                let inParams = DtoDecorator.params[p.in.name];
                Object.keys(inParams).forEach(p => {
                    let item = inParams[p];
                    parameters.push({
                        name: item.name,
                        in: "body",
                        description: item.desc,
                        required: item.options.required,
                        type: "string"
                    })
                })
            }
            if (parameters.length === 1) {
                parameters.push({
                    name: "test",
                    in: "body",
                    description: "占位用不同填",
                    required: false,
                    type: "string"
                })
            }

            this.json.paths[path] = {
                [p.method]: {
                    tags: [element.desc],
                    summary: p.desc,
                    operationId: `${p.funcName}Using${p.method.toUpperCase()}`,
                    consumes: ["x-www-form-urlencoded"],
                    parameters
                }
            }
        })
    }

    /**创建tag */
    public genTags() {
        for (const key in ApiDecorator.prefix) {
            const element = ApiDecorator.prefix[key];
            this.json.tags.push({
                name: element.desc,
                description: element.desc
            })
        }
    }
}